<?php
session_start();
require '../config/config.php';

mydb_connect();

$errmsg_arr = array();
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return $str;
	}
	
	//Sanitize the POST values
	$login = clean($_POST['email']);
	$password = clean($_POST['password']);
	
	//Input Validations
	if($login == '') {
		$errmsg_arr[] = 'Login ID missing';
		$errflag = true;
	}
	if($password == '') {
		$errmsg_arr[] = 'Password missing';
		$errflag = true;
	}

	//If there are input validations, redirect back to the login form
	if($errflag) {
		$_SESSION['ERROR'] = $errmsg_arr;
		session_write_close();
		header("location: ../login.php?login=fail");
		exit();
	}

	else{

	//Create query
	$result = $conn->prepare("SELECT * FROM `users` WHERE email=:email AND password=:password");
	$result->execute(array('email' => $login, 'password' => md5($_POST['password'])));
	//Check whether the query was successful or not
	if($result) {
		
		if($result->rowCount() == 1) {
			//Login Successful

			$member = $result->fetch();
			session_regenerate_id();
			$_SESSION['ADMIN_USER_ID'] = $member['id'];
			$_SESSION['FNAME'] = $member['firstname'];
			$_SESSION['LNAME'] = $member['lastname'];
			session_write_close();
			header("Location: ../index.php");
		}
		else {
			echo "Not registered yet";
		}
	}else {
		die("Query failed: " . $result->errorInfo());
	}
	}
?>